package com.jeesite.modules.app.util.wx;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.alibaba.fastjson.JSONObject;

public class WxUtils {
      public static JSONObject wxDecrypt(String encrypted,String session_key,String iv){
    	  
    	  byte[] dataByte=Base64.decodeBase64(encrypted);
    	  byte[] keyByte=Base64.decodeBase64(session_key);
    	  byte[] iv64=Base64.decodeBase64(iv);
    	  
    	  try {
			int base = 16;
			if(keyByte.length % base !=0){
				int groups=keyByte.length / base + (keyByte.length % base != 0 ? 1:0);
				byte[] temp=new byte[groups * base];
				Arrays.fill(temp, (byte)0);
				System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
				keyByte=temp;
			}
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher=Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
			SecretKeySpec spec=new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters=AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(iv64));
			cipher.init(cipher.DECRYPT_MODE, spec,parameters);
			byte[] resultByte=cipher.doFinal(dataByte);
			if(null != resultByte && resultByte.length > 0){
				String result=new String(resultByte,"UTF-8");
				return JSONObject.parseObject(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	  return null;
      }
      
      public static JSONObject getOpenId(String appid,String appsecret,String code){
    	  String URL="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&js_code=" + code + "&grant_type=authorization_code";
    	  String openId=interfaceUtil(URL,"");
    	  //{"session_key":"UWRXdK\/9PjszdEMzqddAcw==","openid":"oeR6b5SJRvuyTulVDMs0Or05vltw"}
    	  if(StringUtils.isNotBlank(openId)){
    	    JSONObject json=JSONObject.parseObject(openId);
    	    
    	    	return json;
    	   
    	  }
    	  return new JSONObject();
      }
      public static String getToken(String appid,String appsecret,String code){
    	  String URL="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&js_code=" + code + "&grant_type=authorization_code";
    	  String openId=interfaceUtil(URL,"");
    	  //{"session_key":"UWRXdK\/9PjszdEMzqddAcw==","openid":"oeR6b5SJRvuyTulVDMs0Or05vltw"}
    	  if(StringUtils.isNotBlank(openId)){
    	    JSONObject json=JSONObject.parseObject(openId);
    	    if(json.containsKey("openid")){
    	    	String result=json.getString("openid");
    	    	return result;
    	    }
    	  }
    	  return "";
      }
	private static String interfaceUtil(String path, String data) {
		String openId="";
		try {
			URL url=new URL(path);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			PrintWriter out=null;
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out=new PrintWriter(conn.getOutputStream());
			out.println(data);
			out.flush();
			InputStream is = conn.getInputStream();
			BufferedReader br=new BufferedReader(new InputStreamReader(is));
			String str="";
			while((str=br.readLine())!=null){
				openId=str;
			}
			is.close();
			conn.disconnect();			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return openId;
	}
	public static void main(String[] args) {
		String encrypted="mRiq3NAsjLfscIoyQ6q8n/kt5grWYqIiFdW8PZlfR7rmpv05+fLxxPkL6cU9pmddo320wcR3ZHAAWatxMBDEc78D2+J/mBQ2JpFV5CQnwkZZeYXWzSnY+G727MbCjJuXgytBnjoaTpLnVd4lG+Rbgi56jSOLg/Z3xULDjeuLDiUBpDSpOk4Dnp1DuK6xKEpc7hqAwzDgNFIhP2OutRXy0MNasX/rFzvRYrrPGG30BUSvyTWMtkhehB1IWigmEL8SNucWYY2vkAi642t0ZKSdG48JZTwpQiQmQHbXznCDfdFOmlUiZsv4gORTnCTRB9ZcQuFhdAEphcdXlcKyIYEEdJXKDvnRo4ksRVySuMDKdOtkfgNGKnwWIhWX+jWXKGk2R3Fk+Bci9hopz8nfsZO5WycJrCRqlNTy6XistDgnsMJTpA3tN3Kn+ifzCMC8SvIzGCTLEUPGYEfd7f1DKFsY8w==";
		String session_key="kOZdIfPG1/ItHOYNiMjP6g==";
		String iv="5zQTogqgw+8L05y8H6EdTg==";
		JSONObject json=wxDecrypt(encrypted,session_key,iv);
		System.out.println(json);
	}
}
